import Taro, { useRouter } from '@tarojs/taro';
import { useEffect } from 'react';

import { parseJson, RouterUtil } from '@/utils';

export enum ShareType {
  MARKET = 'market',
  PURCHASE = 'purchase',
  COMPANY = 'company',
  INVITATION = 'invitation',
  FOUR_GREAT = 'fourGreat',
  ONLINE = 'online',
}

export const useShareEvent = () => {
  const { shareType, shareParams } = useRouter().params;

  useEffect(() => {
    if (!shareType) return;
    const params = parseJson(shareParams, {});
    handleShare(shareType as ShareType, params);
  }, [shareType, shareParams]);

  // 根据分享参数处理对应事件
  const handleShare = (type: ShareType, params: Record<string, any>) => {
    if (type === ShareType.MARKET) {
      RouterUtil.navigateTo('/pages/market/detail/index', params);
    } else if (type === ShareType.PURCHASE) {
      RouterUtil.navigateTo('/pages/purchase/detail/index', params);
    } else if (type === ShareType.COMPANY) {
      RouterUtil.navigateTo('/packageCompany/pages/index/index', params);
    } else if (type === ShareType.FOUR_GREAT) {
      RouterUtil.navigateTo('/packageFourGreat/pages/detail/index', params);
    } else if (type === ShareType.ONLINE) {
      // 跳转到C端小程序
      Taro.navigateToMiniProgram({
        appId: 'wxf68db7e679fc1fba',
        path: `pages/index/index?shopId=${params.shopId}`,
        envVersion: 'trial',
        success() {
          // 打开成功
          console.log('跳转B小程序成功');
          // 可选：跳转成功后，可以延时关闭当前A小程序页面，提升用户体验
          setTimeout(() => {
            Taro.navigateBack({
              delta: 1, // 返回上一页
              // 如果想直接关闭所有页面回到首页，可以使用 wx.reLaunch
              // wx.reLaunch({ url: '/pages/index/index' })
            });
          }, 1500);
        },
      });
    }
  };

  return {};
};
